﻿/**************************************************
*                      Generic class Menu
**************************************************/
function Menu($div) {
    var that = this;
    var ts = null;
    this.$div = $div;
    this.items = [];

    // create an item using a new closure
    this.createMenu = function (item) {
        var $item = $('<div class="item ' + item.cl + '">' + item.label + '</div>');
        $item
        // bind click on item
                .click(function () {
                    if (typeof (item.fnc) === 'function') {
                        item.fnc.apply($(this), []);
                    }
                })
        // manage mouse over coloration
                .hover(
                    function () { $(this).addClass('hover'); },
                    function () { $(this).removeClass('hover'); }
                );
        return $item;
    }
    // clear timeout
    this.clearTs = function () {
        if (ts) {
            clearTimeout(ts);
            ts = null;
        }
    }
    // init timeout
    this.initTs = function (t) {
        ts = setTimeout(function () { that.close(); }, t);
    }
}

// Add item to menu
Menu.prototype.add = function (label, cl, fnc) {
    this.items.push({
        label: label,
        fnc: fnc,
        cl: cl
    });
}

// Close previous (If having) and open a new menu 
Menu.prototype.open = function (event) {
    this.close();
    var k,
            that = this,
            offset = {
                x: 0,
                y: 0
            },
            $menu = $('<div id="menu"></div>');

    // add items in menu
    for (k in this.items) {
        $menu.append(this.createMenu(this.items[k]));
    }

    // manage auto-close menu on mouse hover / out
    $menu.hover(
              function () { that.clearTs(); },
              function () { that.initTs(3000); }
            );

    // change the offset to get the menu visible (#menu width & height must be defined in CSS to use this simple code)
    if (event.pixel.y + $menu.height() > this.$div.height()) {
        offset.y = -$menu.height();
    }
    if (event.pixel.x + $menu.width() > this.$div.width()) {
        offset.x = -$menu.width();
    }

    // use menu as overlay
    this.$div.gmap3({
        action: 'addOverlay',
        latLng: event.latLng,
        content: $menu,
        offset: offset
    });

    // start auto-close
    this.initTs(5000);
}

// Close the menu
Menu.prototype.close = function () {
    this.clearTs();
    this.$div.gmap3({ action: 'clear', name: 'overlay' })
}